<!-- pages/login/components/passoword.vue -->
<script setup>
	import { ref } from 'vue';
	import { loginByPasswordAPI } from '../../../apis/login';
	import { useUserStore } from '@/stores'

	// 准备响应式数据
	const formData = ref({
		mobile: '',
		password: ''
	})
	
	const form = ref(null)
	
	// 我同意按钮
	const onChecked = ref(false)
	
	// 定义表单校验的规则
	const formRules = {
		mobile: {
			rules: [
				{
					required: true,
					errorMessage: '请输入手机号码',
				},
				{ pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
				 errorMessage: '手机号格式不正确' }
			]
		},
		password: {
			rules: [
				{
					required: true,
					errorMessage: '请输入密码',
				},
				{ pattern: /^[a-zA-z0-9]{8}$/, errorMessage: '密码最少是6到12位数' }
			]
		}
	}
	
	// 点击我同意按钮
	const radioChange = () => {
		onChecked.value = !onChecked.value
	}
	
	// 点击登录按钮
	const onLogin = async () => {
		if(onChecked.value === false) {
			return uni.showToast({
				icon:'none',
				title:'请勾选我同意协议'
			})
		}
		try{
			// 进行表单校验
			await form.value.validate()
			// 发请求
			// console.log(formData.value)
			const { data } = await loginByPasswordAPI(formData.value)
			// 将数据存储到pinia中
			const store = useUserStore()
			// 调用useUserStore中的方法
			store.setUser(data)
			// 登陆成功后跳转页面
			// console.log(store.openType, 909090)
			uni[store.openType]({
				url: store.redirectURL
			})
		}catch(e){
			//TODO handle the exception
			console.log(e)
		}
	}
	
</script>

<template>
  <uni-forms class="login-form" ref="form" :model="formData" :rules="formRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
		v-model="formData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
		v-model="formData.password"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="onChecked" color="#16C2A3" @click="radioChange" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onLogin">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" ">
      忘记密码？
    </navigator>
  </uni-forms>
</template>

<script>
export default {
  options: {
    styleIsolation: 'shared'
  }
}
</script>

<style lang="scss">
@import './styles.scss';
</style>